<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>供应商编辑</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f7f7f7; color: #333; }
        .admin-layout { background-color: #f7f7f7; }
        .content-wrapper { background-color: #fff; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 24px; margin: 20px; }
        .content-header { margin-bottom: 24px; border-bottom: 1px solid #f0f0f0; padding-bottom: 16px; }
        #pageTitle { font-size: 24px; font-weight: 600; color: #333; margin: 0; }
        .form-container { max-width: 600px; margin: 0 auto; }
        .form-group { margin-bottom: 20px; position: relative; }
        .form-label { font-size: 14px; font-weight: 500; color: #666; margin-bottom: 8px; display: block; }
        .required-field::after { content: "*"; color: #dc3545; margin-left: 4px; }
        .form-control, .form-select { height: 44px; border-radius: 10px; border: 1px solid #e0e0e0; padding: 0 16px; font-size: 16px; transition: all 0.2s ease; width: 100%; background-color: #f9f9f9; }
        .form-control:focus, .form-select:focus { border-color: #28a745; box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1); background-color: #fff; outline: none; }
        .btn { height: 44px; border-radius: 10px; font-size: 16px; font-weight: 500; padding: 0 20px; transition: all 0.2s ease; }
        .btn-primary { background-color: #28a745; border-color: #28a745; }
        .btn-primary:hover { background-color: #218838; border-color: #1e7e34; }
        .btn-secondary { background-color: #f2f2f7; border-color: #f2f2f7; color: #28a745; }
        .btn-secondary:hover { background-color: #e5e5ea; border-color: #e5e5ea; }
        .btn-action { min-width: 120px; }
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        @media (max-width: 768px) {
            .content-wrapper { padding: 16px; margin: 10px; }
            .form-container { padding: 0; }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- 顶部导航栏 -->
        <header class="admin-header">
            <div class="header-left">
                <div class="logo">生产过程管理系统</div>
            </div>
            <div class="header-right">
                <span class="user-info">管理员</span>
                <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </header>
        <!-- 左侧菜单 -->
        <aside class="admin-sidebar">
            <ul class="menu-list">
                <li class="menu-item">
                    <a href="../homepage/administrator_home.html">
                        <span class="menu-icon">🏠</span>
                        <span class="menu-title">首页</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">👥</span>
                        <span class="menu-title">人员管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../person/person_list.html">人员列表</a></li>
                        <li><a href="../person/person_edit.html">添加人员</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📦</span>
                        <span class="menu-title">物料管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../material/material_list.html">物料列表</a></li>
                        <li><a href="../material/material_edit.html">添加物料</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">⚙️</span>
                        <span class="menu-title">设备管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../device/device_list.html">设备列表</a></li>
                        <li><a href="../device/device_edit.html">添加设备</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📝</span>
                        <span class="menu-title">产品管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../product/product_list.html">产品列表</a></li>
                        <li><a href="../product/product_edit.html">添加产品</a></li>
                    </ul>
                </li>
                <li class="menu-item active">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">🏢</span>
                        <span class="menu-title">供应商管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="provider_list.html">供应商列表</a></li>
                        <li><a href="provider_edit.html" class="active">添加供应商</a></li>
                    </ul>
                </li>
            </ul>
        </aside>
        <!-- 主内容区域 -->
        <main class="admin-main">
            <div class="content-wrapper">
                <div class="content-header">
                    <h2 id="pageTitle">添加供应商</h2>
                </div>
                <div class="content-body">
                    <div class="form-container">
                        <form id="providerForm">
                            <!-- 移除 id 隐藏字段 -->
                            <div class="form-group">
                                <label for="providerName" class="form-label required-field">供应商名称</label>
                                <input type="text" class="form-control" id="providerName" required>
                            </div>
                            <div class="form-group">
                                <label for="factoryAddress" class="form-label">厂址</label>
                                <input type="text" class="form-control" id="factoryAddress">
                            </div>
                            <div class="form-group">
                                <label for="managerName" class="form-label">经理姓名</label>
                                <input type="text" class="form-control" id="managerName">
                            </div>
                            <div class="form-group">
                                <label for="managerPhone" class="form-label">经理电话</label>
                                <input type="text" class="form-control" id="managerPhone">
                            </div>
                            <div class="form-group">
                                <label for="companyType" class="form-label required-field">企业类型</label>
                                <select class="form-select" id="companyType" required>
                                    <option value="">-- 请选择类型 --</option>
                                    <option value="国有企业">国有企业</option>
                                    <option value="民营企业">民营企业</option>
                                    <option value="外资企业">外资企业</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="registeredCapital" class="form-label">注册资本</label>
                                <input type="number" step="0.01" class="form-control" id="registeredCapital">
                            </div>
                            <div class="form-group">
                                <label for="employeeCount" class="form-label">员工数量</label>
                                <input type="number" class="form-control" id="employeeCount">
                            </div>
                            <div class="form-group">
                                <label for="establishedYear" class="form-label">成立年份</label>
                                <input type="number" min="1900" max="2100" class="form-control" id="establishedYear">
                            </div>
                            <div class="form-group">
                                <label for="providerRating" class="form-label">供应商评级</label>
                                <input type="number" min="1" max="5" class="form-control" id="providerRating" placeholder="1-5分">
                            </div>
                            <div class="form-group">
                                <label for="profile" class="form-label">企业简介</label>
                                <textarea class="form-control" id="profile" rows="3"></textarea>
                            </div>
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-secondary btn-action" onclick="goBack()">返回</button>
                                <button type="submit" class="btn btn-primary btn-action">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <script src="../../assets/js/bootstrap.bundle.min.js"></script>
    <script>
        let isEditMode = false;
        let providerName = null;
        document.addEventListener('DOMContentLoaded', function () {
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });

            // 添加首页链接的点击事件
            document.querySelector('.menu-item:first-child > a').addEventListener('click', function(e) {
                e.preventDefault(); // 阻止默认行为
                window.location.href = '../homepage/administrator_home.html'; // 跳转到管理员首页
            });

            // 默认展开供应商管理菜单
            const providerMenuItem = document.querySelector('.menu-item:nth-child(6)');
            if (providerMenuItem) {
                providerMenuItem.classList.add('active');
            }
            // 设置当前页面对应的菜单项为选中状态
            const currentPath = window.location.pathname;
            const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
            document.querySelectorAll('.submenu li a').forEach(link => {
                if (link.getAttribute('href') === filename) {
                    link.classList.add('active');
                }
            });
            // 检查URL参数，判断是编辑还是新增
            const urlParams = new URLSearchParams(window.location.search);
            providerName = urlParams.get('name');
            if (providerName) {
                isEditMode = true;
                document.getElementById('pageTitle').textContent = '编辑供应商';
                loadProviderData(providerName);
            } else {
                document.getElementById('pageTitle').textContent = '添加供应商';
            }
            document.getElementById('providerForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveProvider();
            });
        });

        async function loadProviderData(name) {
            try {
                const response = await fetch(`http://localhost:8080/api/providers/${encodeURIComponent(name)}`);
                if (!response.ok) throw new Error('获取供应商数据失败');
                const provider = await response.json();
                // 移除对 id 字段的引用
                document.getElementById('providerName').value = provider.providerName || '';
                document.getElementById('factoryAddress').value = provider.factoryAddress || '';
                document.getElementById('managerName').value = provider.managerName || '';
                document.getElementById('managerPhone').value = provider.managerPhone || '';
                document.getElementById('companyType').value = provider.companyType || '';
                document.getElementById('registeredCapital').value = provider.registeredCapital || '';
                document.getElementById('employeeCount').value = provider.employeeCount || '';
                document.getElementById('establishedYear').value = provider.establishedYear || '';
                document.getElementById('providerRating').value = provider.providerRating || '';
                document.getElementById('profile').value = provider.profile || '';
                
                // 编辑模式下禁用供应商名称字段
                if (isEditMode) {
                    document.getElementById('providerName').readOnly = true;
                }
            } catch (error) {
                console.error('加载供应商数据失败:', error);
                alert('加载供应商数据失败，请稍后重试');
            }
        }

        async function saveProvider() {
            const form = document.getElementById('providerForm');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            const providerData = {
                providerName: document.getElementById('providerName').value,
                factoryAddress: document.getElementById('factoryAddress').value,
                managerName: document.getElementById('managerName').value,
                managerPhone: document.getElementById('managerPhone').value,
                companyType: document.getElementById('companyType').value,
                registeredCapital: parseFloat(document.getElementById('registeredCapital').value) || 0,
                employeeCount: parseInt(document.getElementById('employeeCount').value) || 0,
                establishedYear: parseInt(document.getElementById('establishedYear').value) || null,
                providerRating: parseInt(document.getElementById('providerRating').value) || 0,
                profile: document.getElementById('profile').value
            };
            try {
                let url = 'http://localhost:8080/api/providers';
                let method = 'POST';
                if (isEditMode && providerName) {
                    url = `${url}/${encodeURIComponent(providerName)}`;
                    method = 'PUT';
                }
                
                console.log('发送请求到:', url);
                console.log('请求方法:', method);
                console.log('请求数据:', JSON.stringify(providerData));
                
                const response = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(providerData)
                });
                
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('服务器响应错误:', response.status, errorText);
                    throw new Error(`服务器响应错误: ${response.status} - ${errorText || '未知错误'}`);
                }
                
                const result = await response.json();
                alert(result.message || (isEditMode ? '供应商信息更新成功' : '供应商添加成功'));
                window.location.href = 'provider_list.html';
            } catch (error) {
                console.error('保存供应商数据失败:', error);
                alert('保存供应商数据失败: ' + error.message);
            }
        }
        function goBack() {
            window.location.href = 'provider_list.html';
        }
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('userInfo');
                localStorage.removeItem('token');
                window.location.href = '../../../login.html';
            }
        }
    </script>
</body>
</html>